﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UIDispatcher.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the UIDispatcher type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Threading
{
    using System;
    using System.Windows;
    using System.Windows.Threading;

    public class UIDispatcher
    {
        #region Fields

        private static IDispatcher current;

        #endregion

        private class DefaultDispatcher : IDispatcher
        {
            #region Fields

            private Dispatcher _dispatcher;

            #endregion

            private DefaultDispatcher() { }

            public static readonly DefaultDispatcher Instance = new DefaultDispatcher();

            public void BeginInvoke(Action action)
            {
                Dispatcher.BeginInvoke(action);
            }

            public bool CheckAccess()
            {
                return Dispatcher.CheckAccess();
            }

            private Dispatcher Dispatcher
            {
                get
                {
                    if (_dispatcher == null)
                    {
                        _dispatcher =
#if SILVERLIGHT
                            Deployment.Current.Dispatcher;
#else
                            Application.Current.Dispatcher;
#endif
                    }

                    return _dispatcher;
                }
            }
        }

        public static IDispatcher Current
        {
            get { return current ?? DefaultDispatcher.Instance; }
            set { current = value; }
        }
    }
}
